//
//  WebViewController.m
//  WSComponent
//
//  Created by lienbao on 04/09/2014.
//  Copyright (c) 2014 Lienbao. All rights reserved.
//

#import "WSWebViewController.h"
#import "NJKWebViewProgressView.h"
#import "NJKWebViewProgress.h"
#import "UIComponent.h"

CGFloat     const kTooBarHeight       = 44;
CGFloat     const HZProgressBarHeight = 2.5;
NSInteger   const HZProgresstagId     = 222122323;

@interface WSWebViewController () <UIWebViewDelegate, NJKWebViewProgressDelegate>

@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) UIToolbar *toolBar;
@property (nonatomic, strong) UIBarButtonItem *stopButtonItem;
@property (nonatomic, strong) UIBarButtonItem *reloadButtonItem;
@property (nonatomic, strong) UIBarButtonItem *backwardButtonItem;
@property (nonatomic, strong) UIBarButtonItem *forwardButtonItem;
@property (nonatomic, strong) NJKWebViewProgress *progressProxy;

@end

@implementation WSWebViewController

#pragma mark - getter and setter
- (UIWebView *)webView
{
    if (!_webView) {
        _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
        _webView.scalesPageToFit = YES;
        _progressProxy = [[NJKWebViewProgress alloc] init];
        _progressProxy.webViewProxyDelegate = self;
        _progressProxy.progressDelegate = self;
        _webView.delegate = _progressProxy;
        [self.view addSubview:_webView];
    }
    return _webView;
}

#pragma mark - life circle

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupToolBarItems];
    if ([self.absoluteURL length]) {
        [self loadRequest:self.absoluteURL];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadRequest:(NSString *)url
{
    self.absoluteURL = url;
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.absoluteURL]]];
}

- (void)setupToolBarItems
{
    self.webView.frame = CGRectMake(0, 0, self.view.width, self.view.height - kTooBarHeight);
    self.toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.height - kTooBarHeight, self.view.width, kTooBarHeight)];
    self.toolBar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [self.toolBar setBackgroundImage:[UIImage bundleImage:@"toolbarbg"] forToolbarPosition:UIBarPositionBottom barMetrics:UIBarMetricsDefault];
    self.toolBar.tintColor = [UIColor colorWithHex:0x586576 alpha:1.0f];
    [self.view addSubview:self.toolBar];
    
    self.stopButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage bundleImage:@"web_close"]
                                                           style:UIBarButtonItemStylePlain
                                                          target:self.webView
                                                          action:@selector(stopLoading)];
    
    self.reloadButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage bundleImage:@"web_refresh"]
                                                             style:UIBarButtonItemStylePlain
                                                            target:self.webView
                                                            action:@selector(reload)];
    
    self.backwardButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage bundleImage:@"web_back"]
                                                               style:UIBarButtonItemStylePlain
                                                              target:self.webView
                                                              action:@selector(goBack)];
    
    self.forwardButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage bundleImage:@"web_next"]
                                                              style:UIBarButtonItemStylePlain
                                                             target:self.webView
                                                             action:@selector(goForward)];
   
    UIBarButtonItem *returnButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage bundleImage:@"web_return"]
                                                                       style:UIBarButtonItemStylePlain
                                                                      target:self
                                                                      action:@selector(returnButtonClicked:)];
    
    UIBarButtonItem *shareButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage bundleImage:@"web_share"]
                                                                         style:UIBarButtonItemStylePlain
                                                                        target:self
                                                                        action:@selector(shareButtonClicked:)];
    
    UIBarButtonItem *spaceButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                     target:nil
                                                                                     action:nil];
    spaceButtonItem.width = 35.0f;
    
    self.toolbarItems = @[returnButtonItem,
                          spaceButtonItem,
                          self.stopButtonItem,
                          spaceButtonItem,
                          self.backwardButtonItem,
                          spaceButtonItem,
                          self.forwardButtonItem,
                          spaceButtonItem,
                          shareButtonItem];
    
    self.backwardButtonItem.enabled = NO;
    self.forwardButtonItem.enabled = NO;
    [self.toolBar setItems:self.toolbarItems animated:YES];
}

//显示加载进度view
- (NJKWebViewProgressView *)setupHZProgressSubviewWithTintColor:(UIColor *)tintColor
{
    NJKWebViewProgressView *progressView;
	for (UIView *subview in [self.view subviews]) {
		if (subview.tag == HZProgresstagId) {
			progressView = (NJKWebViewProgressView *)subview;
        }
    }
	
	if(!progressView) {
        progressView =  [[NJKWebViewProgressView alloc] initWithFrame:CGRectMake(0, self.webView.top, self.webView.width, HZProgressBarHeight)];
        progressView.tag = HZProgresstagId;
        [self.view addSubview:progressView];
    } else {
		CGRect progressFrame = progressView.frame;
		progressFrame.origin.y = self.webView.top;
		progressView.frame = progressFrame;
    }
	
	return progressView;
    
}
- (void)viewUpdatesForPercentage:(float)percentage andTintColor:(UIColor *)tintColor
{
	NJKWebViewProgressView *progressView = [self setupHZProgressSubviewWithTintColor:tintColor];
    [progressView setProgress:percentage animated:YES];
    return;
}

#pragma mark - button clicked
- (void)returnButtonClicked:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)shareButtonClicked:(id)sender
{
    
}

- (void)toggleState
{
    self.backwardButtonItem.enabled    = self.webView.canGoBack;
    self.forwardButtonItem.enabled = self.webView.canGoForward;
    NSMutableArray *toolbarItems = [self.toolbarItems mutableCopy];
    if (self.webView.loading) {
        toolbarItems[2] = self.stopButtonItem;
    } else {
        toolbarItems[2] = self.reloadButtonItem;
    }
    self.toolbarItems = [toolbarItems copy];
    [self.toolBar setItems:self.toolbarItems animated:YES];
}

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    DLog(@"++++++request:%@", [[request URL] absoluteString]);
    if ([[[request URL] absoluteString] isEqualToString:@"http://m.dianping.com/tuan"]) {
        [self .navigationController popViewControllerAnimated:YES];
        return YES;
    }
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [self toggleState];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self toggleState];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
   [self toggleState];
}

#pragma mark NJKWebViewProgressDelegate
- (void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    if(progress >= 1.0000f) {
       self.webView.backgroundColor = [UIColor clearColor];
    }
    [self viewUpdatesForPercentage:progress andTintColor:[UIColor redColor]];
}
@end
